<!--
 * @Author: 小陆同学 1361176289@qq.com
 * @Date: 2024-08-01 11:01:58
 * @LastEditors: 小陆同学 1361176289@qq.com
 * @LastEditTime: 2024-08-14 09:52:22
 * @FilePath: \loCode\src\components\prBarcode\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<div class="prBarcode" :style="style">
		<img :id="getCurBarcodeId"></img>
	</div>
</template>

<script setup>
	import { onMounted, nextTick, computed, watch } from "vue";
	import JsBarcode from "jsbarcode";
	import {generateRandomString} from '@/utils'

	const props = defineProps({
		text: String,
		// 标题样式
		style: {
			type: Object,
			default: () => {},
		},
		// 条码配置
		barcode: {
			type: Object,
			default: () => {
				return {
					displayValue: true, //是否在条形码下方显示文字
					fontSize: 15, //设置文本的大小
					margin: 15, //设置条形码周围的空白边距
				};
			},
		},
	});

	watch(
		() => [props.text, props.barcode, props.style.height, props.style.width],
		() => drawBarcode(),
		{ deep: true }
	);



	// 随机生成字符串包括大小写
	const getCurBarcodeId = computed(() => generateRandomString(20));

	onMounted(() => drawBarcode());

	// 绘制条形码
	const drawBarcode = async () => {
		if (!props.text) return;
		const { displayValue, fontSize, margin, fontOptions } = props.barcode;
		await nextTick();
		JsBarcode(`#${getCurBarcodeId.value}`, String(props.text), {
			//设置条之间的宽度
			width: 1,
			//设置条形码的高度
			height: Number(props.style.height.replace("px", "")) - 30,
			//是否在条形码下方显示文字
			displayValue: displayValue,
			//使文字加粗体或变斜体
			fontOptions: fontOptions,
			//设置文本的大小
			fontSize: fontSize,
			//设置条形码周围的空白边距
			margin: margin
		});
		await nextTick();
	};
</script>

<style lang="scss" scoped>
	.prBarcode {
		display: flex;
		justify-content: center;
		align-items: center;
		user-select: none;
	}
</style>
